package com.cy.controller;

import com.cy.controller.ex.*;
import com.cy.entity.User;
import com.cy.service.IUserService;

import com.cy.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    public IUserService userService;

    /*
    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        //创建响应结果对象
        JsonResult<Void> result=new JsonResult<>();
        try {
            userService.reg(user);
            result.setState(200);
            result.setMessage("成功");
        } catch (UsernameDuplicatedException e) {
           result.setState(400);
           result.setMessage("用户名被占用");
        }catch (InsertException e)
        {
            result.setState(500);
            result.setMessage("位置异常");
        }
        return result;
    }

     */

    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password,
                                  HttpSession session)
    {
        User data=userService.login(username,password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());

        System.out.println(getuidFromSession(session));
        System.out.println(getUsernameFromSession(session));

        return new JsonResult<User>(OK,data);
    }

    @RequestMapping("/change_password")
    public JsonResult<Void>changePassword(String oldPassword,
                                          String  newPassword,
                                          HttpSession session)
    {
        Integer uid = getuidFromSession(session);
        String username=getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);

    }


    @RequestMapping("/get_by_uid")
    public JsonResult<User> getByUid(HttpSession session)
    {
        User data=userService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK,data);

    }


    @RequestMapping("/change_info")
    public JsonResult<Void>changeInfo(User user,
                                      HttpSession session)
    {
        Integer uid=getuidFromSession(session);
        String username=getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    /**
     * MultipartFile springmvc 提供接口获取文件（接受任何数据）
     * springmvc 在需要处理请求方法上添加一个参数类型MultipartFile
     * 参数 然后springboot自动将数据赋值给这个参数
     * @param session
     * @param file
     * @return
     */
    //设置文件上传最大值
    public static final int AVATAR_MAX_SIZE=10*1024*1024;

    public static final List<String> AVATAR_TYPE=new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file") MultipartFile file){
        if(file.isEmpty())
        {
            throw new FileEmptyException("文件不存在");
        }

        if(file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("大小超限");
        }
        String contentType = file.getContentType();
        if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件格式错误");
        }

        String parent = session.getServletContext().getRealPath("upload");
//文件操作
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
//让图片的名称唯一
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);

        int index=originalFilename.lastIndexOf(".");
        String suffix=originalFilename.substring(index);
        String filename= UUID.randomUUID().toString()+suffix;

        File dest=new File(dir,filename);
        //参数file中数据写入这个空文件 file 文件数据写入 复制
        try {
            file.transferTo(dest);
        }catch (FileStateException e){
            throw new FileStateException("文件状态异常");
        }
        catch (IOException e) {
            throw new FileUploadException("文件读写异常");
        }
        Integer uid=getuidFromSession(session);
        String username=getUsernameFromSession(session);
        String avatar="/upload/"+filename;

        userService.changeAvatar(uid,avatar,username);
        //返回路径给前端用于展示
        return new JsonResult<>(OK, avatar);


    }


}
